#!/bin/sh

getlinecount() {
        wc -l "$1" | cut -d " " -f 1
}


syntax() {
	printf "$0 filename linenumber content\n"
	printf "will insert content (quote it propery) into filename at line linenumber + 1\n"
	exit 1
}

insert_line() {
        local file="$1"
        local lineno="$2"
        local content="$3"
	[ -z "$1" ] && syntax
	[ -z "$2" ] && syntax
	[ -z "$3" ] && syntax

        local numlines=`getlinecount "$file"`
        local restlines=`echo "$numlines - $lineno" | bc`
        local tmpfile=`printf "/tmp/insline.%.8d.%.8d" $RANDOM $RANDOM`

        head -n $lineno "$file" > $tmpfile
        printf "%s\n" "$content" >> $tmpfile
        tail -n $restlines "$file" >> $tmpfile
        mv $tmpfile "$file"
}

insert_line "$@"

